import 'package:flutter/material.dart';
import '/models/receiving_api_response.dart';
import 'package:http/http.dart' as http;
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart'; 
import 'dart:convert';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';

class ReceivingDetailScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;

  const ReceivingDetailScreen({super.key, required this.jsonData});

  @override
  _ReceivingDetailScreenState createState() => _ReceivingDetailScreenState();
}

class _ReceivingDetailScreenState extends State<ReceivingDetailScreen> {
  bool _isButtonEnabled = false;
  Receivingobj? _receivingobj;
  String? selectedLpn;
  final TextEditingController lpnController = TextEditingController();
  bool _isLoading = false;
  bool _isReadOnly = false;
  Map<String, String> orderDetails = {};
  List<String> availableLpns = [];
  Map<String, dynamic>? _lastScannedData;
  late int? shipmentLineId;
  List<ReceivedShipmentLine> receivedShipmentLines = [];
  final FocusNode _barcodeFocusNode = FocusNode();
  
  int? warehouseId;
  int selectedIndex = 0;
  late double _fontScale;

  @override
  void initState() {

    super.initState();

    lpnController.addListener(_updateButtonState);
    
    // 解析API返回数据
    _receivingobj = Receivingobj.fromJson(widget.jsonData);
    
    // 初始化订单详情
    orderDetails = {
      'Order': _receivingobj?.orderInfo.orderNumber??'N/A',
      'Order Type': _receivingobj?.orderInfo.orderType??'N/A',
      'Shipment': _receivingobj?.shipmentCode??'N/A',
      'Total LNPs': _receivingobj?.totalLpns.toString()??'N/A',
      'Received': _receivingobj?.received.toString()??'N/A',
    };
    
    // 初始化可用LPN列表
    availableLpns = _receivingobj?.receivedShipmentLines
        ?.map((line) => line.lpnNumber)
        .toList()??[];

    receivedShipmentLines = _receivingobj?.receivedShipmentLines??[];

    // 设置默认选中的LPN
    if (availableLpns.isNotEmpty) {
      // selectedLpn = availableLpns.first;
      // lpnController.text = selectedLpn!;
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_barcodeFocusNode);
    });
  }

  @override
  void dispose() {
    lpnController.dispose();
    lpnController.removeListener(_updateButtonState);
    lpnController.dispose();
    _barcodeFocusNode.dispose();
    super.dispose();
  }

  void _updateButtonState() {
    final hasText = lpnController.text.trim().isNotEmpty;
    if (_isButtonEnabled != hasText) {
      setState(() {
        _isButtonEnabled = hasText;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    return Scaffold(
      appBar: AppBar(
        title: Text('Receiving Detail',style: TextStyle(fontSize: 18 * _fontScale),),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pushNamed(context, '/inbound/receiving'),
        ),  
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      body: Column(
        children: [
          // 订单信息部分
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: _buildOrderDetails(),
            ),
          ),
          
          // 可用LPN标题
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.0),
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Available LPN(s):',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
          ),
          const SizedBox(height: 8),
          
          // LPN单选列表
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 16.0),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey, width: 1.0),
                borderRadius: BorderRadius.circular(4.0),
              ),
              child: ListView.builder(
                itemCount: availableLpns.length,
                itemBuilder: (context, index) {
                  final lpn = availableLpns[index];
                  return RadioListTile<String>(
                    dense: true, // 使用紧凑布局
                    contentPadding: const EdgeInsets.only(left: 0), // 减少左侧内边距
                    title: Align( // 添加对齐控制
                      alignment: Alignment.centerLeft,
                      child: Text(
                        lpn,
                        style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
                      ),
                    ),
                    value: lpn,//原本是lpn
                    activeColor:  Colors.transparent,
                    groupValue: lpn,//原本是selectedLpn
                    onChanged: (value) {
                      // setState(() {
                      //   selectedLpn = value;
                      //   lpnController.text = value!;
                      //   selectedIndex = index;
                      //   shipmentLineId = receivedShipmentLines[index].id;
                      // });
                    },
                  );
                },
              ),
            ),
          ),
          
          // 底部输入区域
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    focusNode: _barcodeFocusNode,
                    readOnly: _isReadOnly,
                    controller: lpnController,
                    decoration: const InputDecoration(
                      labelText: 'LPN Number',
                      border: OutlineInputBorder(borderRadius: BorderRadius.zero),
                      contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                    ),
                    onChanged: (value) => _updateButtonState(),
                    onSubmitted: _handleSubmitted,
                    onTap: (){
                      // 点击时全选内容
                      if (lpnController.text.isNotEmpty) {
                        lpnController.selection = TextSelection(
                          baseOffset: 0,
                          extentOffset: lpnController.text.length,
                        );
                      }
                    },
                  ),
                ),
                SizedBox(
                  height: 48,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(0),
                      ),
                      backgroundColor: _isButtonEnabled 
                          ? const Color(0xFF008363) 
                          : Colors.grey,
                    ),
                    onPressed: _isButtonEnabled && !_isLoading?() {_handleSubmitted(lpnController.text);} : null,
                    child: _isLoading ? 
                    const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        color: Colors.white,
                      ),
                    ) :
                    const Text(
                      'GO',
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Colors.white),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建订单信息行
  List<Widget> _buildOrderDetails() {
    return orderDetails.entries.map((entry) {
      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 4.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              width: 120,
              child: Text(
                '${entry.key}:',
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                entry.value,
                style: const TextStyle(fontSize: 16),
              ),
            ),
          ],
        ),
      );
    }).toList();
  }

  void _parseBarcode(String value) {
    try {
      print('value--$value');
      final jsonData = json.decode(value) as Map<String, dynamic>;
      if (jsonData.containsKey('lpn_number')) {
        setState(() {
          _lastScannedData = jsonData;
          if (jsonData['lpn_number'] != null && 
              jsonData['lpn_number'].toString().isNotEmpty) {
            lpnController.text = jsonData['lpn_number'].toString();
          }
        });
      }
      if(jsonData.containsKey('shipment_line_id')){
        shipmentLineId = jsonData['shipment_line_id'];
      }
      // 点击时全选内容
      if (lpnController.text.isNotEmpty) {
        lpnController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: lpnController.text.length,
        );
      }
    } catch (e) {
      _lastScannedData = null;
      shipmentLineId = null;
    }
  }

  // 提交LPN的方法
  void _handleSubmitted(String value) async {
    if (_isLoading) return;
    setState(() => _isLoading = true);
    setState(() => _isReadOnly = true);

    try {
      _parseBarcode(value);

      if(_lastScannedData == null){
        MessageBox.showMessageBox(context,'Invalid QR Code, please scan again.',isError:true);
        return;
      }
      
      // 2. 调用API
      final details = await _updateReceivingLPN(
        id:_receivingobj!.id,
        shipmentLineId:shipmentLineId,
        lpnNumber:value,
        status: 'Received'
      );
      
      if (!mounted) return;
      
      // 3. 处理API响应
      if (details['code'] == 2000) {
        MessageBox.showMessageBox(context,details['msg'],isError:false);
        setState(() {
          if(details['data'].isNotEmpty){
            print('data----${details['data']}');
            _receivingobj = Receivingobj.fromJson(details['data']) ;
            print('_receivingobj----$_receivingobj');
            availableLpns = _receivingobj?.receivedShipmentLines
              ?.map((line) => line.lpnNumber)
              .toList()??[];
          }
          selectedLpn = null;
          _lastScannedData = null;
          shipmentLineId = null;
        });
      } else {
        MessageBox.showMessageBox(context,details['msg'],isError:true);
      }
    } catch (e) {
      if (!mounted) return;
      MessageBox.showMessageBox(context,e,isError:false);
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
        setState(() => _isReadOnly = false);
      }
    }
  }

  // 调用API更新收货详情
  Future<Map<String, dynamic>> _updateReceivingLPN({
    int? id,
    int? shipmentLineId,
    required String lpnNumber,
    required String status
  }) async {
    // 确保_receivingobj不为空
    if (_receivingobj == null) {
      throw Exception('Receiving object is null');
    }

    // 构建URL
    final apiUrl = '${ApiService.baseURL}${ApiService.updateReceiving}$id/';

    // 获取access token
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw Exception('The session has expired, Please log in again.');
    }
    
    try {
      // 构建请求体
      final requestBody = {
        'shipment_line_id': shipmentLineId,
        'lpn_number': lpnNumber,
        'status': status,
      };
      
      print('Sending PUT request to: $apiUrl');
      print('Request body: $requestBody');
      
      final response = await http.put(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
        body: jsonEncode(requestBody),
      );
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('API response: $jsonData');
        
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else if (jsonData['code'] == 401) {
          authService.logout(context); // 使用现有的authService实例
          throw Exception('The session has expired, Please log in again.');
        } else {
          throw Exception('Failed to load data: ${jsonData['msg']}');
        }
      } else {
        throw Exception('HTTP Error: ${response.statusCode} - ${response.body}');
      }
    } catch (e) {
      print('API call failed: $e');
      throw Exception('API call failed: $e');
    }
  }
}